package com.xywei.config.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

@Component("securityCustomAuthenticationFailureHandler")
public class SecurityCustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {

		String errorMessage = null;

		String exceptionName = exception.getCause() == null ? exception.getClass().getSimpleName()
				: exception.getCause().getClass().getSimpleName();
		System.out.println(exceptionName);

		switch (exceptionName) {
		case "BadCredentialsException":
			errorMessage = "用户名或者密码错误！";
			break;
		case "DisabledException":
			errorMessage = "用户状态异常！";
			break;
		default:
			errorMessage = "服务器繁忙！";
			break;
		}

		if (exception instanceof BadCredentialsException) {
		} else if (exception instanceof DisabledException) {
		}
		request.setAttribute("errorMessage", errorMessage);
		request.getRequestDispatcher("/userLoginPage").forward(request, response);
	}

}
